<template>
  <div>
    <Dialog :loading="loading" :title="title" :visible="visible" class="two-columns" :button-text="textBtn" @close="handleClose" @confirm="submitForm">
      <UserInfo v-if="customerId" :info-id="addConsultingForm.customerId" />
      <el-form ref="consultingFormRef" :model="addConsultingForm" :rules="subscribeRules" label-width="100px">
        <el-row type="flex">
          <el-row>
            <el-col>
              <el-col :span="12">
                <el-form-item v-if="!customerId" label="顾客：" prop="customerName">
                  <el-autocomplete v-model="addConsultingForm.customerName" :fetch-suggestions="querySearch" placeholder="姓名、手机号、编号" clearable @select="handleSelect" />
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="12">
              <el-form-item label="咨询分类：" prop="consultTypeName" class="el-select-y">
                <el-cascader v-model="addConsultingForm.consultTypeName" style="width:100%" :options="consultingOptions" :props="optionsProps" @change="handleCascader" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item style="width: 100%" label="需求1：" prop="oneDemand">
                <el-cascader
                  v-model="addConsultingForm.oneDemand"
                  :options="optionsData"
                  :props="propsOption"
                  style="width:100%"
                  @change="handleChange($event,'1')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item style="width: 100%" label="需求2：" prop="towDemand">
                <el-cascader
                  v-model="addConsultingForm.towDemand"
                  :options="optionsData"
                  :props="propsOption"
                  style="width:100%"
                  @change="handleChange($event,'2')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item style="width: 100%" label="需求3：" prop="threeDemand">
                <el-cascader
                  v-model="addConsultingForm.threeDemand"
                  :options="optionsData"
                  :props="propsOption"
                  style="width:100%"
                  @change="handleChange($event,'3')"
                />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="咨询情况：">
                <editor-content class="editor__content box-y" :editor="editor" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="咨询结果：" prop="result">
                <el-radio-group v-model="addConsultingForm.result">
                  <el-radio label="上门">上门</el-radio>
                  <el-radio label="不上门">不上门</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col v-if="addConsultingForm.result==='上门'">
              <el-form-item label="预约：" prop="switchType">
                <el-switch v-model="addConsultingForm.switchType" />
              </el-form-item>
            </el-col>
            <el-col v-if="addConsultingForm.switchType&&addConsultingForm.result==='上门'">
              <el-col>
                <el-col :span="12">
                  <el-form-item label="预约时间：" prop="appointmentDate">
                    <el-col :span="13">
                      <el-form-item prop="appointmentDate" class="dateStyle">
                        <el-date-picker v-model="addConsultingForm.appointmentDate" :picker-options="pickerOptions" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期" @change="handleDate" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="11">
                      <el-form-item prop="appointmentTime" class="dateStyle">
                        <el-select v-model="addConsultingForm.appointmentTime" class="el-select-y" placeholder="请选择时段" clearable>
                          <el-option v-for="item in cities" :key="item.id" :label="item.value" :value="item.value" :disabled="item.label === '不可预约' ? true : false">
                            <span style="float: left">{{ item.value }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.label }}</span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-form-item>
                </el-col>
              </el-col>
              <el-col>
                <el-col :span="12">
                  <el-form-item label="咨询师：" prop="consultantName" class="el-select-y">
                    <el-select v-model="addConsultingForm.consultantName" placeholder="请选择" clearable @change="handleConsultant">
                      <el-option v-for="item in consultantOptions" :key="item.id" :label="item.usrName" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-col>
              <el-col>
                <el-form-item label="预约说明：" prop="appointmentRemark">
                  <el-input v-model="addConsultingForm.appointmentRemark" class="border-y" type="textarea" resize="none" :autosize="{ minRows: 3 }" />
                </el-form-item>
              </el-col>
            </el-col>
            <el-col v-if="addConsultingForm.result==='不上门'">
              <el-col>
                <el-form-item label="不上门原因：" prop="loseReason">
                  <el-checkbox-group v-model="addConsultingForm.loseReason">
                    <el-checkbox v-for="(item,i) in loseReasons" :key="i" :label="item.name" />
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="设定回访：">
                  <el-row v-for="(item,i) in ReturnVisitRules" :key="i">
                    <el-col>
                      默认计划{{ i+1 }}：第{{ item.returnDay }}天
                    </el-col>
                  <!-- <el-col>
                    回访时间：{{ item.rebackTime }} 回访人：{{ item.returnName }}
                  </el-col> -->
                  </el-row>
                  <ul>
                    <!-- <li v-for="(items,i) in plainData" :key="i">
                    <span>
                      计划{{ i+1 }}
                    </span>
                    <el-row type="flex">
                      <el-col :span="11">
                        <el-form-item label="回访日期：" prop="rebackTime">
                          <el-date-picker v-model="items.rebackTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd hh:m:mm" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="10">
                        <el-form-item label="回访人：" prop="rebackMan">
                          <el-select v-model="items.rebackMan" placeholder="选择回访人" value-key="id">
                            <el-option v-for="item of consultantOptions" :key="item.id" :label="item.usrName" :value="item" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="1">
                        <el-button type="text" @click="deletePlain(i)">删除</el-button>
                      </el-col>
                    </el-row>
                  </li> -->
                    <li v-for="(items,i) in plainData" :key="i">
                      <span>
                        <!-- 计划{{ i+1 }} -->
                        计划{{ i+1+ReturnVisitRules.length }}
                      </span>
                      <el-row type="flex" style="width:600px">
                        <el-col :span="11">
                          <el-form-item label="回访日期：" prop="rebackTime">
                            <el-date-picker v-model="items.rebackTime" :picker-options="pickerOptions" type="date" placeholder="选择日期" value-format="yyyy-MM-dd hh:m:mm" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="10">
                          <el-form-item label="回访人：" prop="returnId">
                            <el-select v-model="items.returnId" class="el-select-y" placeholder="选择回访人" @change="rebackManChangeValue($event,i)">
                              <el-option v-for="item of consultantOptions" :key="item.id" :label="item.usrName" :value="item" />
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="2" :offset="1">
                          <el-popconfirm
                            title="这是一段内容确定删除吗？"
                            @confirm="deletePlain(i)"
                          >
                            <el-button slot="reference" type="text">删除</el-button>
                          </el-popconfirm>
                        </el-col>
                      </el-row>
                    </li>
                    <el-button class="buttons" @click="addPlain">+ 增加计划</el-button>
                  </ul>
                </el-form-item>
              </el-col>
            </el-col>
          </el-row>
        </el-row>
      </el-form>
    </Dialog>
  </div>
</template>
<script>
import Dialog from "@/components/Dialog/index";
import { Editor, EditorContent } from "tiptap";
import UserInfo from "@/components/UserInformation";
export default {
  components: {
    Dialog,
    EditorContent,
    UserInfo,
  },
  props: {
    title: {
      type: String,
      default: '',
    },
    textBtn: {
      type: String,
      default: '',
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          const times = Date.now() - 24 * 60 * 60 * 1000;
          return time.getTime() < times;
        },
      },
      propsOption: {
        value: 'id',
        label: 'dataName',
        checkStrictly: true,
      },
      optionsData: [],
      loseReasons: [], // 不上门原因数组
      addConsultingForm: {
        result: '上门',
        loseReason: [],
      },
      restaurants: [],
      plainData: [
        // {
        //   rebackTime: '',
        //   id: this.$store.getters.currentUserInfo.id,
        //   rebackMan: this.$store.getters.currentUserInfo.usrName,
        // },
      ],
      optionsProps: {
        children: "children",
        label: "name",
        value: "id",
        checkStrictly: true, // 选择任意一项
      },
      consultingOptions: [],
      consultantOptions: [],
      seleteDate: "", // 预约选择日期
      cities: [], // 预约时段
      editor: null,
      ReturnVisitRules: [],
      templateData: {},
      loading: false,
      subscribeRules: {
        customerName: [
          { required: true, message: "请输入顾客名称", trigger: "change" },
        ],
        consultTypeName: [
          { required: true, message: "请选择咨询分类", trigger: "blur" },
        ],
        appointmentDate: [
          { required: true, message: "请选择预约时间", trigger: "change" },
        ],
      },
      customerId: "",
    };
  },
  mounted() {
    // this.getTemplate();
    this.getDicoptList();
    this.getTreeProject();
    this.getVisitRuleList();
  },
  methods: {
    getVisitRuleList() {
      this.$api["doctor/consulting/allVisitRuleList"]({ query: { type: '未成交回访' }}).then((res) => {
        if (res.code !== 200) return this.$message.error("查询列表回访规则失败");
        this.ReturnVisitRules = res.data;
        this.ReturnVisitRules.forEach(item => {
          const dates = new Date(new Date(item.createdTime).valueOf() + 24 * 60 * 60 * 1000 * Number(item.returnDay));
          const year = dates.getFullYear();
          const month = dates.getMonth() + 1;
          const day = dates.getDate();
          const rebackTime = year + "-" + month + "-" + day;
          this.$set(item, 'rebackTime', rebackTime);
        });
      });
    },
    rebackManChangeValue(id, i) {
      // 选择回访人
      this.consultantOptions.forEach(item => {
        if (item.id === id) {
          this.plainData[i].returnName = item.usrName;
        }
      });
      // this.addConsultingForm.rebackMan = val.usrName;
    },
    handleChange(val, aa) {
      if (val && val.length > 0) {
        const nameList = [];
        let list = this.optionsData;
        val.forEach(item => {
          list.forEach(json => {
            if (item === json.id) {
              nameList.push(json.dataName);
              if (json.children) list = json.children;
            }
          });
        });
        if (!this.addConsultingForm.demandDtos) {
          this.addConsultingForm.demandDtos = [{
            'projectName': nameList.join(">"),
            'projectId': val.join(","),
            'lastProjectId': val[val.length - 1],
            'adviserId': this.addConsultingForm.adviserId,
            'customerCode': this.addConsultingForm.customerCode,
            'customerId': this.addConsultingForm.customerId,
            'customerName': this.addConsultingForm.customerName,
            'customerPhone': this.addConsultingForm.customerPhone,
            'demandSort': aa,
          }];
          return false;
        }
        let bools = false;
        this.addConsultingForm.demandDtos.forEach((item, i) => {
          if (item.demandSort === aa) {
            bools = true;
            const changeItem = {
              'projectName': nameList.join(">"),
              'projectId': val.join(","),
              'lastProjectId': val[val.length - 1],
              'adviserId': this.addConsultingForm.adviserId,
              'customerCode': this.addConsultingForm.customerCode,
              'customerId': this.addConsultingForm.customerId,
              'customerName': this.addConsultingForm.customerName,
              'customerPhone': this.addConsultingForm.customerPhone,
              'demandSort': aa,
            };
            this.addConsultingForm.demandDtos[i] = changeItem;
          }
        });
        if (!bools) {
          this.addConsultingForm.demandDtos.push({
            'projectName': nameList.join(">"),
            'projectId': val.join(","),
            'lastProjectId': val[val.length - 1],
            'adviserId': this.addConsultingForm.adviserId,
            'customerCode': this.addConsultingForm.customerCode,
            'customerId': this.addConsultingForm.customerId,
            'customerName': this.addConsultingForm.customerName,
            'customerPhone': this.addConsultingForm.customerPhone,
            'demandSort': aa,
          });
        }
      }
    },
    getTreeProject() { // 获取意向项目的多级联动数据
      this.$api["data/goods/treeList"]({ dataType: '项目类' }).then((res) => {
        if (res.code !== 200) return;
        this.optionsData = res.data;
      });
    },
    getDicoptList() {
      // 查询不上门原因的数据
      this.$api["seting/siteConsul/getDicoptList"]({
        query: { dictionaryId: "798215514336788480" },
      }).then((res) => {
        if (res.code !== 200) return this.$message.error("查询不上门原因失败");
        this.loseReasons = res.data.optionList;
      });
    },
    // 增加咨询
    addConsulting(customer) {
      this.customerId = "";
      if (customer) {
        this.getTemplate();
        this.addConsultingForm.loseReason = [];
        this.$set(this.addConsultingForm, 'customerName', customer.name || customer.customerName);
        this.$set(this.addConsultingForm, 'customerId', customer.id || customer.customerId);
        if (this.addConsultingForm.oneDemand) this.addConsultingForm.oneDemand = this.addConsultingForm.oneDemand.split(',');
        if (this.addConsultingForm.towDemand) this.addConsultingForm.towDemand = this.addConsultingForm.towDemand.split(',');
        if (this.addConsultingForm.threeDemand) this.addConsultingForm.oneDethreeDemandmand = this.addConsultingForm.threeDemand.split(',');
        this.customerId = this.addConsultingForm.customerId;
      }
      this.getConsulting();
      this.getFindall();
      this.attributionConsultant();
    },
    // 所有顾客详情
    async getFindall() {
      const res = await this.$api["reception/subscribe/findall"]();
      if (res.code === 200) {
        res.data.map((item) => {
          item.value = item.name;
        });
        this.restaurants = res.data;
      }
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      this.addConsultingForm.customerId = item.id;
    },
    // 咨询分类
    async getConsulting() {
      const res = await this.$api["reception/subscribe/consulttype"]();
      if (res.code === 200) {
        this.consultingOptions = res.data.result;
      }
    },
    handleCascader(val) {
      this.consultingOptions.map(item => {
        if (item.id === val[0]) {
          this.addConsultingForm.consultTypeName = item.name;
          this.addConsultingForm.consultTypeId = item.id;
        }
      });
    },
    // 咨询师
    async attributionConsultant() {
      const res = await this.$api['data/hospitalStaff/getAllByJobName']({ hospitalJobName: "咨询师" });
      if (res.code !== 200) return;
      this.consultantOptions = res.data;
    },
    // 选中的咨询师
    handleConsultant(id) {
      this.addConsultingForm.consultantId = id;
      this.consultantOptions.map(item => {
        if (item.id === id) {
          this.addConsultingForm.consultantName = item.usrName;
        }
      });
    },
    getTemplate() {
      this.$api["networkpower/consultationsetup/list"]({ 'templateType': '网电咨询模板' }).then((res) => {
        if (res.code !== 200) return this.$message.error("获取咨询模板失败");
        this.templateData = res.data;
        this.editor = new Editor({
          content: this.templateData.template,
          onUpdate: ({ state, getHTML, getJSON, transaction }) => {
            this.templateData.template = getHTML();
          },
        });
      });
    },
    // 监听选中预约日期变化
    async handleDate() {
      function p(s) { return s < 10 ? "0" + s : s; }
      const myDate = new Date();
      const year = myDate.getFullYear();
      const month = myDate.getMonth() + 1;
      const day = myDate.getDate();
      const hours = myDate.getHours();
      const minutes = myDate.getMinutes();
      const dates = year + "-" + p(month) + "-" + p(day) + "-" + p(hours) + "-" + p(minutes);
      const currentDate = dates.split("-").join("");
      if (this.addConsultingForm.appointmentDate) {
        // 预约时段列表
        const timeData = await this.$api["reception/subscribe/getCreateList"]({ dictionaryId: "785558903319429120" });
        if (timeData.code !== 200) return this.$message.error(timeData.message);
        timeData.data.map((item) => {
          item.value = item.name + "-" + item.content;
          const aTime = this.addConsultingForm.appointmentDate + "-" + item.content;
          const bTime = aTime.split(":").join("");
          this.seleteDate = bTime.split("-").join("");
          if (Number(currentDate) > Number(this.seleteDate)) {
            item.label = "不可预约";
          } else {
            item.label = "可预约";
          }
        });
        this.cities = timeData.data;
      }
    },
    submitForm() {
      this.$refs.consultingFormRef.validate(async(valid) => {
        if (valid) {
          // if (this.addConsultingForm.consultTypeName) {
          //   this.addConsultingForm.consultTypeName = this.addConsultingForm.consultTypeName[0];
          // }
          if (this.plainData.length > 0) {
            this.plainData.map(item => {
              if (item.rebackMan.id) {
                item.id = item.rebackMan.id;
              }
              item.rebackMan = item.rebackMan.usrName;
            });
          }
          this.addConsultingForm.advisoryType = "网电咨询";
          if (this.addConsultingForm.switchType) {
            this.addConsultingForm.isAppointment = "是";
          } else {
            this.addConsultingForm.isAppointment = "否";
          }
          this.addConsultingForm.loseReason = this.addConsultingForm.loseReason.join(',');
          this.addConsultingForm.simpleDtoList = this.plainData;
          if (this.addConsultingForm.oneDemand) this.$set(this.addConsultingForm, "oneDemand", this.addConsultingForm.oneDemand.toString());
          if (this.addConsultingForm.towDemand) this.$set(this.addConsultingForm, "towDemand", this.addConsultingForm.towDemand.toString());
          if (this.addConsultingForm.threeDemand) this.$set(this.addConsultingForm, "threeDemand", this.addConsultingForm.threeDemand.toString());
          this.ReturnVisitRules.forEach(item => {
            item.returnId = item.id;
            this.addConsultingForm.simpleDtoList.push(item);
          });
          this.loading = true;
          const res = await this.$api['doctor/consulting/addProduct']({ ...this.addConsultingForm });
          if (res.code !== 200) return this.$message.error("新增网电咨询模板失败");
          this.$emit("update:visible", false);
          this.$emit('success');
          this.$message.success("新增成功");
          this.$refs.consultingFormRef.resetFields();
          this.loading = false;
        }
      });
    },
    handleClose() {
      this.$emit("update:visible", false);
      this.$refs.consultingFormRef.resetFields();
      this.loading = false;
      this.addConsultingForm.switchType = false;
      this.editor.destroy();
      this.plainData = [
        {
          rebackTime: '',
          rebackMan: '',
        },
      ];
    },
    // 增加计划
    addPlain() {
      this.plainData.push({
        rebackTime: '',
        rebackMan: '',
      },);
    },
    // 删除计划
    deletePlain(index) {
      this.plainData.splice(index, 1);
    },
  },
};
</script>
<style lang="scss" scoped>
.dateStyle {
  margin-bottom: 0;
}
.border-y{
  border: 1px solid #D3DFF7;
  border-radius: 5px;
}
/deep/.el-textarea__inner:hover{
  border-color: #D3DFF7;
}
.el-textarea__inner{
  border: none !important;
}
/deep/ .el-autocomplete .el-input{
  width: 237.5px;
}
/deep/ .el-form-item .el-form-item__label{
  text-align: right !important;
}

.buttons{
  width: 84px;
  height: 30px;
  background: #EFF3FB !important;
  border-radius: 2px;
  font-size: 14px;
  font-weight: 500;
  padding: 0;
  text-align: center;
  color: #0278DC !important;
  border: none;
}
/deep/.ProseMirror p{
  margin: 0px !important;
}
</style>
